package demo.controller;

import com.sun.org.apache.bcel.internal.generic.NEW;
import demo.dao.UserMapper;
import jdbc.DBUtil;
import jdbc.InputUtil;
import jdbc.UserInfo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 控制器
 * 用于根据用户的不同需求调用不同的业务操作
 * */
public class UserController {
    public static void main(String[] args) {
        UserController userController = new UserController();
        userController.start();

    }
    private UserMapper userMapper = new UserMapper();
    // 启动
    public void start(){
        System.out.println("欢迎使用用户管理系统");
        System.out.println("请输入要进行操作的编号:");
        System.out.println("[1]:用户注册");
        System.out.println("[2]:用户登录");
        System.out.println("[3]:修改密码");
        Scanner scanner = new Scanner(System.in);
        String num = scanner.nextLine();
        switch (num){
            case "1":
                regUser();
                break;
            case "2":
                loginUser();
                break;
            case "3":
                changePWD();
                break;
            default:
                System.out.println("输入有误，请重新输入");
                start();
                break;
        }
    }
    // 登录用户
    public void loginUser(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("欢迎登录");
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();

        UserInfo userInfo = userMapper.findByUsername(username);
        if(userInfo==null||!userInfo.getPassword().equals(password)){
            System.out.println("用户名或密码输入有误，登录失败");
        }else{
            System.out.println("登录成功，欢迎回来:"+userInfo.getNickname());
        }

    }
    // 注册用户
    public void regUser() {
        UserInfo userInfo = InputUtil.getInputObject(new UserInfo(), "用户注册");
        if (userMapper.findByUsername(userInfo.getUsername()) != null) {
            System.out.println("该用户已存在");
        } else {
            userMapper.insert(userInfo);
            System.out.println("注册成功");
        }
    }
    // 修改密码
    public void changePWD(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名");
        String username = scanner.nextLine();
        System.out.println("请输入旧密码");
        String oblpassword = scanner.nextLine();
        UserInfo userInfo = userMapper.findByUsername(username);
        if(userInfo == null || ! oblpassword.equals(userInfo.getPassword())){
            System.out.println("用户名或密码错误");
        }else {
            System.out.println("请输入新密码");
            String newpassword = scanner.nextLine();
            userInfo.setPassword(newpassword);
            userMapper.update(userInfo);
            System.out.println("修改成功");
        }
    }



}
